import type { UserConfig, ConfigEnv } from 'vite';
import pkg from './package.json';
import dayjs from 'dayjs';
import { loadEnv } from 'vite';
import { resolve } from 'path';
import { createProxy } from './build/vite/proxy';
import { wrapperEnv } from './build/utils';
import { createVitePlugins } from './build/vite/plugin';
import { include, exclude } from './build/vite/optimize'

function pathResolve(dir: string) {
  return resolve(process.cwd(), '.', dir);
}

const { dependencies, devDependencies, name, version } = pkg;
const __APP_INFO__ = {
  pkg: { dependencies, devDependencies, name, version },
  lastBuildTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
};

export default ({ command, mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();

  const env = loadEnv(mode, root);

  // 关联环境，环境配置
  const viteEnv = wrapperEnv(env);

  const { VITE_PORT, VITE_PUBLIC_PATH, VITE_DROP_CONSOLE } = viteEnv;
  console.log('mode=%s, root=%s, env=%s', mode, root, env);
  const isBuild = command === 'build';

  return {
    base: VITE_PUBLIC_PATH,
    root,
    server: {
      https:false,
      open: false, //自动打开
      // Listening on all local IPs
      host: true,
      port: VITE_PORT,
      // Load proxy configuration from .env
      proxy: createProxy(viteEnv),
      // proxy:{
      //   "/api/train" :{
      //     target: "http://127.0.0.1:8080",
      //     changeOrigin: true,
      //     rewrite: (path) => path.replace(/^\/api\/tain/, ''),//路径处理
      //   }
      // }
    },
    resolve: {
      alias: [
        {
          find: 'vue-i18n',
          replacement: 'vue-i18n/dist/vue-i18n.cjs.js',
        },
        {
          find: /@\//,
          replacement: pathResolve('src') + '/',
        },
      ],
    },
    esbuild: {
      drop: VITE_DROP_CONSOLE ? ['console', 'debugger'] : [],
    },
    build: {
      //target: 'es2015',
      //cssTarget: 'chrome80',
      cssCodeSplit: true, // css代码分隔，false会在构建在同一个文件
      reportCompressedSize: false,
      chunkSizeWarningLimit: 2000,
    },
    define: {
      __APP_INFO__: JSON.stringify(__APP_INFO__),
    },

    // 相关插件，单独管理
    plugins: createVitePlugins(viteEnv, isBuild),

    optimizeDeps: { include, exclude },
  };
};
